package com.gxa.jjty.admin.service.impl;

import com.gxa.jjty.admin.service.RecitalService;
import com.gxa.jjty.core.common.ExceptionCode;
import com.gxa.jjty.core.exception.BusinessException;
import com.gxa.jjty.core.pojo.Recital;
import com.gxa.jjty.core.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.common.Mapper;

/**
 * @author asus
 */
@Service
@Transactional(rollbackFor = Throwable.class)
public class RecitalServiceImpl extends BaseServiceImpl<Recital> implements RecitalService {

    @Autowired
    Mapper<Recital> recitalMapper;

    @Autowired
    RedisTemplate redisTemplate;


    ListOperations listOps = null;

    @Override
    public Recital selectById(Long id) throws BusinessException {
        Recital recital = recitalMapper.selectByPrimaryKey(id);
        if (recital == null){
            throw new BusinessException(ExceptionCode.SCORE_NO_EXIST);
        }
        return recital;
    }

    @Override
    public void updateRecitalService(Recital recital) throws BusinessException {
        listOps = redisTemplate.opsForList();
        recitalMapper.selectByPrimaryKey(recital.getId());
        listOps.remove("recitalList",1,recital);
        int i = recitalMapper.updateByPrimaryKeySelective(recital);
        if (i !=1){
            throw new BusinessException(ExceptionCode.UPDATE_FALSE);
        }
        listOps.rightPush("recitalList",recital);
    }

    @Override
    public void deleteById(Long id) throws BusinessException {
        listOps = redisTemplate.opsForList();
        Recital recital = recitalMapper.selectByPrimaryKey(id);
        listOps.remove("recitalList",1,recital);
        int i = recitalMapper.deleteByPrimaryKey(id);
        if (i != 1){
            throw  new BusinessException(ExceptionCode.DELETE_FALSE);
        }
        System.out.println("i:"+i);
    }

    @Override
    public void insertRecital(Recital recital) throws BusinessException {
        listOps = redisTemplate.opsForList();
        int i = recitalMapper.insertSelective(recital);
        if (i != 1){
            throw  new BusinessException(ExceptionCode.ADD_DEFEATED);
        }
        Long recitalList = listOps.rightPush("recitalList", recital);

    }
}
